package com.hushao.aimi.service.impl;

import com.hushao.aimi.common.ServerResponse;
import com.hushao.aimi.entity.UserRole;
import com.hushao.aimi.vo.UserVo;
import com.hushao.aimi.repository.UserRepository;
import com.hushao.aimi.repository.UserRoleRepository;
import com.hushao.aimi.service.UserService;
import com.hushao.aimi.entity.AimiUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @description: 用户服务
 * @author: 胡少
 * @create: 2018-06-03 21:36
 **/

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserRoleRepository userRoleRepository;



    @Override
    public ServerResponse getUserInfo(String username) throws Exception {
        AimiUser user=userRepository.findByUsername(username);
        UserVo userVo=new UserVo(user.getUsername(),user.getImage(),user.getPhone(),user.getEmail());
        return ServerResponse.Success(userVo);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ServerResponse register(UserVo userVo)throws Exception{
        AimiUser u=userRepository.findByUsername(userVo.getUsername());
        if(u!=null){
            log.error("用户名已被注册：{}",u.getUsername());
            return ServerResponse.Error("用户名已被注册!");
        }
        AimiUser user=new AimiUser(userVo.getUsername(),userVo.getPassword(),userVo.getPhone(),null);
        AimiUser s=userRepository.save(user);
        UserRole userRole=new UserRole(s.getId(),1,null);
        userRoleRepository.save(userRole);
        log.info("注册用户：{}成功！",user.getUsername());
        return ServerResponse.Success("注册成功！");
    }

    @Override
    public ServerResponse valid(String username, String phone) {
        if(username!=null){
            AimiUser aimiUser=userRepository.findByUsername(username);
            if (aimiUser!=null){
                return ServerResponse.Error("用户名已被注册");
            }
        }
        if (phone!=null){
            AimiUser aimiUser=userRepository.findByPhone(phone);
            if (aimiUser!=null){
                return ServerResponse.Error("手机号已被使用");
            }
        }
        return ServerResponse.Success();
    }
}
